<template>
  <div class="frame" @click="selected">
    <span :class="{ text: checkLable }">{{
      checkLable ? checkLable : placeholder
    }}</span>
    <span class="clearFix">{{ showSelect ? "1" : "2" }}</span>
  </div>
  <div v-if="showSelect" class="optionsWrap">
    <div
      class="options"
      v-for="item in myOptionList"
      :key="item.value"
      @click="checkOption(item)"
      :class="{ activeOption: item.disabled === '' || item.disabled }"
    >
      {{ item.lable }}
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
import Option from "./option.vue";

export default defineComponent({
  props: {
    placeholder: { type: String, default: "请选择" },
  },
  setup(props, context) {
    const showSelect = ref<boolean>(false);

    const defaults: any = context.slots.default?.()[0].children;

    defaults?.map((item: any) => {
      if (item.type !== Option) {
        throw new Error("请使用正确的子标签");
      }
    });

    const myOptionList = defaults?.map((item: any) => {
      return item.props;
    });

    const selected = () => {
      showSelect.value = !showSelect.value;
    };

    interface checkObj {
      lable: string;
      value: number;
      disabled: boolean;
    }
    const checkLable = ref<string>("");
    const checkOption = (item: checkObj) => {
      if (!item.disabled) {
        checkLable.value = item.lable;
        showSelect.value = false;
      }
    };

    return { myOptionList, selected, showSelect, checkOption, checkLable };
  },
});
</script>
<style scoped lang="scss">
.frame {
  border: 1px solid grey;
  width: 150px;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  :first-child {
    color: grey;
    font-size: 14px;
  }
  :last-child {
    float: right;
  }
  .text {
    color: black;
    font-size: 14px;
  }
}
.optionsWrap {
  border: 1px solid grey;
  width: 200px;
  margin-top: 10px;
  max-height: 300px;
  overflow: auto;
  padding: 10px 0;
  .options {
    cursor: pointer;
    padding: 4px 6px;
    &:hover {
      background: grey;
      color: white;
    }
  }
  .activeOption {
    background: #dadada;
    color: grey;
    cursor: not-allowed;
  }
  &::before {
    content: "";
    display: inline-block;
    transform: rotate(45deg);
    border-left: 1px solid grey;
    border-top: 1px solid grey;
    position: absolute;
    top: 121px;
    left: 154px;
    width: 10px;
    height: 10px;
  }
}
</style>
